﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdbService
{
    /// <summary>
    /// ADB进程管理器
    /// </summary>
    public static class AdbProcessManager
    {
        /// <summary>
        /// 杀死所有ADB相关进程
        /// </summary>
        public static void KillAllAdbProcesses()
        {
            try
            {
                // 要杀死的进程名称列表
                string[] processNames = { "adb", "cmd", "conhost" };

                foreach (string processName in processNames)
                {
                    try
                    {
                        var processes = Process.GetProcessesByName(processName);
                        foreach (var process in processes)
                        {
                            try
                            {
                                if (!process.HasExited)
                                {
                                    process.Kill();
                                    process.WaitForExit(1000);
                                    Debug.WriteLine($"已终止进程: {process.ProcessName} (PID: {process.Id})");
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine($"终止进程 {process.ProcessName} 失败: {ex.Message}");
                            }
                            finally
                            {
                                process.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"获取进程 {processName} 失败: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"杀死ADB进程时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查是否有ADB进程在运行
        /// </summary>
        public static bool IsAnyAdbProcessRunning()
        {
            try
            {
                return Process.GetProcessesByName("adb").Any() ||
                       Process.GetProcessesByName("cmd").Any(p => IsAdbRelatedProcess(p));
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 判断进程是否与ADB相关
        /// </summary>
        private static bool IsAdbRelatedProcess(Process process)
        {
            try
            {
                // 这里可以添加更精确的判断逻辑
                return process.ProcessName.ToLower().Contains("cmd") &&
                       process.MainWindowTitle.ToLower().Contains("adb");
            }
            catch
            {
                return false;
            }
        }
    }
}
